package com.sunk.ytmall.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.sunk.ytmall.common.Result;
import com.sunk.ytmall.entity.User;
import com.sunk.ytmall.entity.dto.UserLoginRegisterForgerDTO;
import com.sunk.ytmall.osscloud.OSSFactory;
import com.sunk.ytmall.service.ICommonInfoService;
import com.sunk.ytmall.service.IUserService;
import com.sunk.ytmall.utils.SHA1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @Author: Sunk
 * @Date: 2018/4/17 16:01
 * @Description:用于对用户的操作
 */
@RestController
@RequestMapping("/users")
public class UserController{

    //成功登陆checkOut
    private final static Integer USER_SUCCESS=1001;
    //账号已经存在
    private final static Integer USER_ALREADY=1002;
    //登陆失败，密码错误
    private final static Integer USER_FAILD=1003;
    //账号不存在
    private final static Integer USER_NO_ACCOUNT=1002;
    //session中User标识
    private final static String USER="user";
    @Autowired
    IUserService userService;
    @Autowired
    private ICommonInfoService commonInfoService;
    /**
     * 用户登陆
     * @param userLoginRegisterForgerDTO
     * @return
     */
    @PostMapping("/login")
    public Result userLogin(@RequestBody UserLoginRegisterForgerDTO userLoginRegisterForgerDTO,
                            HttpServletRequest request,HttpServletResponse response){
        Result result=new Result();
        //1.账后是否存在 true 存在 false不存在
        if(!checkUserAccount(userLoginRegisterForgerDTO)){
            result.setSuccess(false);
            result.setCode(USER_NO_ACCOUNT);
            result.setMessage("账号不存在");
            return  result;
        }
        //2.数据库查询
        User u=userService.selectOne(
                new EntityWrapper<User>()
                        .eq("user_account", userLoginRegisterForgerDTO.getUserAccount())
                        .eq("user_password", SHA1.encode(userLoginRegisterForgerDTO.getUserPassword()))

        );
        if(u!=null){
            result.setSuccess(true);
            result.setMessage("登陆成功");
            result.setCode(USER_SUCCESS);
            result.setResult(u);
            //3.存入session
            Cookie cookie= null;
            try {
                cookie = new Cookie(USER, URLEncoder.encode(JSON.toJSONString(u), "utf-8"));
//                cookie = new Cookie(USER, JSON.toJSONString(u));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //1天
            cookie.setMaxAge(24*60*60);
            response.addCookie(cookie);
            request.getSession().setAttribute(USER,u);
        }else{
            result.setSuccess(false);
            result.setCode(USER_FAILD);
            result.setMessage("密码错误");
        }
        return  result;
    }
    //账后是否存在 true 存在 false不存在
    private Boolean checkUserAccount(UserLoginRegisterForgerDTO userLoginRegisterForgerDTO) {
        User user=userService.selectOne(
                new EntityWrapper<User>()
                        .eq("user_account", userLoginRegisterForgerDTO.getUserAccount()
                        )
        );
        if(user==null)
            return false;
        return true;
    }

    @RequestMapping("/loginOut")
    public Result loginOut(@RequestBody String json,HttpServletRequest request,HttpServletResponse response){
        Result result=new Result();
        request.getSession().setAttribute(USER, null);
        response.addCookie(new Cookie(USER,null));
        result.setSuccess(true);
        result.setMessage("注销成功");
        return  result;
    }

    /**
     * 用于检测用户是否登陆
     */
    @RequestMapping("userInfo")
    public Result checkOut(HttpServletRequest request){
        Result result=new Result();
        User u= (User) request.getSession().getAttribute(USER);
        if(u!=null){
            result.setSuccess(true);
            result.setResult(u);
        }else{
            result.setSuccess(false);
            result.setResult("");
            result.setMessage("未登录");
        }
        return result;
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @RequestMapping("register")
    public Result userRegister(@RequestBody User user){
        Result result=new Result();
        UserLoginRegisterForgerDTO userLoginRegisterForgerDTO =new UserLoginRegisterForgerDTO();
        userLoginRegisterForgerDTO.setUserAccount(user.getUserAccount());
        if(checkUserAccount(userLoginRegisterForgerDTO)){
            result.setSuccess(false);
            result.setCode(USER_ALREADY);
            result.setMessage("账号已经存在");
            return  result;
        }
        try {
            user.setUserPassword(SHA1.encode(user.getUserPassword()));
            user.setUserImage("image/zhijia.jpg");
            user.setCreateTime(new Date());
            user.setUserName(user.getUserAccount());
            user.setUpdateTime(new Date());
            userService.insert(user);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("注册失败:"+e.getMessage());
            return result;
        }
        result.setSuccess(true);
        return  result;
    }
    @Autowired
    OSSFactory ossFactory;

    /**
     * 上传头像
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws Exception {
        Result result=new Result();
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件不能为空");
        }

        //上传文件
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String url = ossFactory.build().uploadSuffix(file.getBytes(), suffix);

        //保存文件信息
        User u=commonInfoService.getUser();
        u.setUserImage(url);
        userService.updateById(u);
        result.setResult(u);
        result.setSuccess(true);
        return result;
    }

    @PostMapping("/updateUserInfo")
    public Result updateUser(@RequestBody User user){
        Result result=new Result();
        User u=commonInfoService.getUser();
        user.setUserId(u.getUserId());
        user.setUpdateTime(new Date());
        user.setUserPassword(SHA1.encode(user.getUserPassword()));
        userService.updateById(user);
        result.setSuccess(true);
        result.setResult(userService.selectById(u.getUserId()));
        return result;
    }
}
